import tornado.web
from tornado.options import options
import datetime
from PyWebsite3.common import float_2_percentage, df_float_formated
import MutualFundScore.load_data as load_data
import json
import pandas as pd


class RenderMutualFundPageHandler(tornado.web.RequestHandler):
    def get(self, path):
        symbol = path
        # symbol = "000001.OF"
        database = options.database
        datetime_update = datetime.datetime.now()

        # 读取基金快照表
        fund_filter = {"symbol": symbol}
        fund_document = database.Find("financial_data", "instrument_mutualfund", filter=fund_filter)
        fund_document = fund_document[0]

        # 读取基金净值
        daily_bar_document = {}
        datetime2 = datetime.datetime.now()
        datetime1 = datetime2 - datetime.timedelta(days=1 * 365)
        fund_filter = [("symbol", symbol), ("date", ">", datetime1), ("date", "<", datetime2)]
        df_daily_bar = database.GetDataFrame("financial_data", "mutualfund_dailybar", filter=fund_filter, sort=[("date",1)])
        if not df_daily_bar.empty:
            df_daily_bar["s_date"] = df_daily_bar["date"].apply(lambda x: x.strftime('%Y-%m-%d'))
            #
            daily_bar_document["date"] = list(df_daily_bar["s_date"])
            daily_bar_document["price"] = list(df_daily_bar["adjusted_net_asset_value"])
        else:
            daily_bar_document["date"] = []
            daily_bar_document["price"] = []

        # 读取行业暴露
        five_industry_document = {}
        exposure_filter = [("symbol", symbol), ("date", ">", datetime1), ("date", "<", datetime2)]
        df_five_industry_exposure = database.GetDataFrame("derivative_data", "mutualfund_five_industry_style_exposure", filter=exposure_filter, sort=[("date", 1)])
        if not df_five_industry_exposure.empty:
            df_five_industry_exposure["s_date"] = df_five_industry_exposure["date"].apply(lambda x: x.strftime('%Y-%m-%d'))
            df_float_formated(df_five_industry_exposure, fields=["finance_beta", "period_beta", "growth_beta", "consume_beta", "medicine_beta"], keep_float=4)
            #
            five_industry_document["date"] = list(df_five_industry_exposure["s_date"])
            five_industry_document["finance_beta"] = list(df_five_industry_exposure["finance_beta"])
            five_industry_document["period_beta"] = list(df_five_industry_exposure["period_beta"])
            five_industry_document["growth_beta"] = list(df_five_industry_exposure["growth_beta"])
            five_industry_document["consume_beta"] = list(df_five_industry_exposure["consume_beta"])
            five_industry_document["medicine_beta"] = list(df_five_industry_exposure["medicine_beta"])
        else:
            pass

        # 读取风格暴露
        sharpe_exposure_document = {}
        exposure_filter = [("symbol", symbol), ("date", ">", datetime1), ("date", "<", datetime2)]
        df_sharpe_exposure = database.GetDataFrame("derivative_data", "mutualfund_sharpe_style_exposure", filter=exposure_filter, sort=[("date", 1)])
        if not df_sharpe_exposure.empty:
            df_sharpe_exposure["s_date"] = df_sharpe_exposure["date"].apply(lambda x: x.strftime('%Y-%m-%d'))
            df_float_formated(df_sharpe_exposure, fields=["finance_beta", "period_beta", "growth_beta", "consume_beta", "medicine_beta"], keep_float=4)
            #
            sharpe_exposure_document["date"] = list(df_sharpe_exposure["s_date"])
            sharpe_exposure_document["large_cap_growth_beta"] = list(df_sharpe_exposure["large_cap_growth_beta"])
            sharpe_exposure_document["large_cap_value_beta"] = list(df_sharpe_exposure["large_cap_value_beta"])
            sharpe_exposure_document["small_cap_growth_beta"] = list(df_sharpe_exposure["small_cap_growth_beta"])
            sharpe_exposure_document["small_cap_value_beta"] = list(df_sharpe_exposure["small_cap_value_beta"])
        else:
            pass

        # 读取报告
        filter = [("symbol", symbol)]
        df_report = database.GetDataFrame("financial_data", "mutualfund_report", filter=filter, sort=[("report_date", -1)])
        df_report = df_report.iloc[0]
        report_date = df_report["report_date"]
        total_aum = df_report["net_asset"]

        # 读取持仓
        df_stock_list = database.GetDataFrame("financial_data", "instrument_stock", projection=["symbol", "description"], sort=[("symbol", 1)])

        filter = [("mutualfund", symbol), ("report_date", report_date)]
        df_positions = database.GetDataFrame("financial_data", "mutualfund_positions", filter=filter)
        if not df_positions.empty:
            df_positions = pd.merge(df_positions, df_stock_list, how="left", on="symbol")
            df_positions["ratio"] = df_positions["equity"] / total_aum
        position_document = df_positions.to_dict("records")

        #
        self.render("mutualfund.html",
                    fund_document=fund_document,
                    daily_bar_document=daily_bar_document,
                    position_document=position_document,
                    sharpe_exposure_document=sharpe_exposure_document,
                    five_industry_exposure_document=five_industry_document)
